import torch
import torch.nn as nn 
class ECAModule(nn.Module):
    def __init__(self, channel, gamma=2, b=1):
        super(ECAModule, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        kernel_size = int(abs((torch.log2(torch.tensor(channel, dtype=torch.float32)) + b) / gamma))
        kernel_size = kernel_size if kernel_size % 2 == 1 else kernel_size + 1
        self.conv1d = nn.Conv1d(1, 1, kernel_size=kernel_size, padding=(kernel_size - 1) // 2, bias=False)

    def forward(self, x):
        y = self.avg_pool(x)
        y = y.squeeze(-1).transpose(-1, -2)
        y = self.conv1d(y)
        y = y.transpose(-1, -2).unsqueeze(-1)
        y = torch.sigmoid(y)
        return x * y.expand_as(x)
    
class ECABottleneck(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1):
        super(ECABottleneck, self).__init__()
        self.expansion = 4
        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.conv3 = nn.Conv2d(out_channels, out_channels * self.expansion, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(out_channels * self.expansion)
        self.eca = ECAModule(channel=out_channels * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = None
        if stride != 1 or in_channels != out_channels * self.expansion:
            self.downsample = nn.Sequential(
                nn.Conv2d(in_channels, out_channels * self.expansion, kernel_size=1, stride=stride),
                nn.BatchNorm2d(out_channels * self.expansion))
    def forward(self, x):
        identity = x
        x = self.bn1(self.conv1(x))
        x = self.relu(x)
        x = self.bn2(self.conv2(x))
        x = self.relu(x)
        x = self.bn3(self.conv3(x))
        out = self.eca(x)
        if self.downsample is not None:
            identity = self.downsample(identity)
        out += identity
        out = self.relu(out)
        return out
class ECANet(nn.Module):

    def __init__(self, blocks_num, num_classes=10):
        super(ECANet, self).__init__()
        self.in_channel = 64

        self.conv = nn.Conv2d(3, self.in_channel, kernel_size=3,padding=1)
        self.bn = nn.BatchNorm2d(self.in_channel)
        self.relu = nn.ReLU()
        self.maxpool = nn.MaxPool2d(kernel_size=3,stride=2,padding=1)        
        self.layer1 = self._make_layer(64, blocks_num[0])
        self.layer2 = self._make_layer(128, blocks_num[1], stride=2)
        self.layer3 = self._make_layer(256, blocks_num[2], stride=2)
        self.layer4 = self._make_layer(512, blocks_num[3], stride=2)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * 4, num_classes)
        # self._init_weight()

    def _make_layer(self, out_channel, block_num, stride=1):
        layers = []
        layers.append(ECABottleneck(self.in_channel, out_channel, stride=stride))
        self.in_channel = out_channel * 4
        for i in range(1, block_num):
            layers.append(ECABottleneck(self.in_channel, out_channel))
        return nn.Sequential(*layers)
    
    # def _init_weight(self):
    #     for m in self.modules():
    #         if isinstance(m, nn.Conv2d):
    #             nn.init.kaiming_normal_(m.weight, mode = 'fan_out', nonlinearity = 'relu')
    #         elif isinstance(m, nn.BatchNorm2d):
    #             nn.init.constant_(m.weight, 1)
    #             nn.init.constant_(m.bias, 0)

    def forward(self, x):
        x = self.bn(self.conv(x))
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)

        return x